/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
/*
 * This copy of Woodstox XML processor is licensed under the
 * Apache (Software) License, version 2.0 ("the License").
 * See the License for details about distribution rights, and the
 * specific rights regarding derivate works.
 *
 * You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/
 *
 * A copy is also included in the downloadable source code package
 * containing Woodstox, in file "ASL2.0", under the same directory
 * as this file.
 */
package com.je.bpm.engine.impl.cmd;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.event.StartEvent;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.core.model.task.KaiteCounterSignUserTask;
import com.je.bpm.core.model.task.KaiteMultiUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.bpmn.behavior.KaiteBaseUserTaskActivityBehavior;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntityImpl;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.Comment;
import com.je.bpm.engine.task.Task;
import com.je.bpm.engine.upcoming.ActivitiUpcomingRun;
import com.je.bpm.engine.upcoming.UpcomingCommentInfoDTO;

import java.util.*;

/**
 * 撤回命令
 * 1. 从历史任务重查找上一个任务处理节点。
 * 2. 获取节点定义KEY，和指派人。
 * 3. 设置目标节点，设置指派人变量。
 * 4. 流程继续流转，执行跳转逻辑（不能顺序流转的原因有的时候跳跃或者驳回都是跳跃节点，所以，取回的实现也要是跳跃的）。
 */
public class WithdrawTaskCmd extends AbstractJumpTask {

    private String comment;

    private String beanId;

    public WithdrawTaskCmd(String taskId, String prod, Map<String, Object> bean, String comment, String beanId) {
        super(taskId, prod, bean);
        this.taskId = taskId;
        this.comment = comment;
        this.beanId = beanId;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    @Override
    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    @Override
    public Void execute(CommandContext commandContext, TaskEntity taskEntity) {
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(taskEntity.getProcessDefinitionId());
//        executeBeforeHandler(bpmnModel, taskEntity, CustomEvent.CustomEventEnum.TASK_RETRIEVE_BEFORE, comment, OperatorEnum.TASK_RETREIEVE_OPERATOR, "");

        List<Task> list = commandContext.getProcessEngineConfiguration().getTaskService()
                .createTaskQuery().processInstanceId(taskEntity.getProcessInstanceId()).list();

        if (Strings.isNullOrEmpty(comment)) {
            comment = String.format("(%s)任务撤回", Authentication.getAuthenticatedUser().getName());
        } else {
            comment = String.format("(%s)", Authentication.getAuthenticatedUser().getName()) + comment;
        }

        for (Task task : list) {
            commandContext.getProcessEngineConfiguration().getTaskService().addComment(task.getId(), taskEntity.getProcessInstanceId(),
                    Comment.NODE_TYPE, "撤回");
            commandContext.getProcessEngineConfiguration().getTaskService().addComment(task.getId(), taskEntity.getProcessInstanceId(),
                    Comment.USER_COMMENT, comment);
        }

        ExecutionEntity execution = taskEntity.getExecution();

        //执行清理首页待办逻辑
        List<TaskEntity> taskEntityList = commandContext.getProcessEngineConfiguration().getTaskEntityManager()
                .findTasksByProcessInstanceId(execution.getProcessInstanceId());
        List<String> taskIds = new ArrayList<>();
        for (TaskEntity task : taskEntityList) {
            taskIds.add(task.getId());
        }
        ActivitiUpcomingRun activitiUpcomingRun = commandContext.getProcessEngineConfiguration().getActivitiUpcomingRun();
        UpcomingCommentInfoDTO upcomingInfo = DelegateHelper.buildUpcomingInfo(null, "", SubmitTypeEnum.WITHDRAW,
                beanId, String.join(",", taskIds), null);
        upcomingInfo.setPiid(taskEntity.getProcessInstanceId());
        activitiUpcomingRun.completeUpcoming(upcomingInfo);


        FlowElement flowElement = bpmnModel.getFlowElement(taskEntity.getTaskDefinitionKey());

        KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;

        StartEvent startEvent = findStartEvent(bpmnModel.getMainProcess().getFlowElements());

        String firstTaskRef = startEvent.getOutgoingFlows().get(0).getTargetRef();
        //找到第一个任务节点
        KaiteBaseUserTask targetBaseUserTask = (KaiteBaseUserTask) bpmnModel.getFlowElement(firstTaskRef);

        //删除任务之前调用审批告知
        Context.getCommandContext().getProcessEngineConfiguration().getProcessInstanceHelper()
                .addApprovalNotificationVariable(bpmnModel, kaiteBaseUserTask.getId(), comment, SubmitTypeEnum.WITHDRAW.getName());

        //删除所有的任务
        List<ExecutionEntityImpl> list1 = (List<ExecutionEntityImpl>) taskEntity.getProcessInstance().getExecutions();
        for (ExecutionEntityImpl executionEntity : list1) {
            if (!Strings.isNullOrEmpty(executionEntity.getBusinessKey())) {
                continue;
            }
            String nodeId = executionEntity.getActivityId();
            if (nodeId.startsWith("countersign") || nodeId.startsWith("batchtask")) {
                deleteAllMultiTask(commandContext, executionEntity);
            } else {
                List<TaskEntity> tasks = executionEntity.getTasks();
                for (TaskEntity taskEntity1 : tasks) {
                    commandContext.getTaskEntityManager().deleteTask(taskEntity1, comment, false, false);
                }
            }
        }

        if (execution == null) {
            throw new ActivitiException("撤回任务异常，请联系管理员！");
        }


        if (kaiteBaseUserTask instanceof KaiteCounterSignUserTask || kaiteBaseUserTask instanceof KaiteMultiUserTask) {
            execution = (ExecutionEntity) getMultiInstanceRootExecution(execution);
        }

        JSONArray jsonArray = new JSONArray();
        JSONObject assigneeUserJsonObject = new JSONObject();
        assigneeUserJsonObject.put("nodeId", targetBaseUserTask.getId());
        assigneeUserJsonObject.put("nodeName", targetBaseUserTask.getName());
        assigneeUserJsonObject.put("assignee", Authentication.getAuthenticatedUser().getDeptId());
        assigneeUserJsonObject.put("assigneeName", Authentication.getAuthenticatedUser().getName());
        jsonArray.add(assigneeUserJsonObject);
        UpcomingCommentInfoDTO upcomingInfo2 = UpcomingCommentInfoDTO.build
                (SubmitTypeEnum.WITHDRAW, Context.getCommandContext().getBean(), taskEntity.getBusinessKey(),
                        comment, taskId, null, jsonArray.toJSONString());
        Context.getCommandContext().addAttribute(KaiteBaseUserTaskActivityBehavior.UPCOMINGINFO, upcomingInfo2);


        execution.setCurrentFlowElement(targetBaseUserTask);
        Map<String, Object> transientVariables = new HashMap<>();
        transientVariables.put(targetBaseUserTask.getId(), Authentication.getAuthenticatedUser().getDeptId());
        execution.setTransientVariables(transientVariables);
        Context.getAgenda().planContinueProcessOperation(execution);
//        executeAfterHandler(bpmnModel, taskEntity, CustomEvent.CustomEventEnum.TASK_RETRIEVE_AFTER, comment, OperatorEnum.TASK_RETREIEVE_OPERATOR, "");

        return null;
    }

    protected DelegateExecution getMultiInstanceRootExecution(DelegateExecution executionEntity) {
        DelegateExecution multiInstanceRootExecution = null;
        DelegateExecution currentExecution = executionEntity;
        while (currentExecution != null && multiInstanceRootExecution == null && currentExecution.getParent() != null) {
            if (currentExecution.isMultiInstanceRoot()) {
                multiInstanceRootExecution = currentExecution;
            } else {
                currentExecution = currentExecution.getParent();
            }
        }
        return multiInstanceRootExecution;
    }

    private StartEvent findStartEvent(Collection<FlowElement> elements) {
        StartEvent startEvent = null;
        for (FlowElement eachElement : elements) {
            if (eachElement instanceof StartEvent) {
                startEvent = (StartEvent) eachElement;
                break;
            }
        }
        return startEvent;
    }

}
